package com.jk.lesson2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Auser on 2016/11/8.
 */
public class AppleTest {
    public static void main(String[] args){
        List<Apple> apples = new ArrayList<>();
        Apple apple1 = new Apple("green", 100);
        Apple apple2 = new Apple("green", 150);
        Apple apple3 = new Apple("green", 200);
        Apple apple4 = new Apple("red", 100);
        Apple apple5 = new Apple("red", 150);
        Apple apple6 = new Apple("red", 200);
        Apple apple7 = new Apple("red", 250);
        apples.add(apple1);
        apples.add(apple2);
        apples.add(apple3);
        apples.add(apple4);
        apples.add(apple5);
        apples.add(apple6);
        apples.add(apple7);

        List<Apple> greenApples = filterApples(apples, new AppleGreenColorPredicate());
        System.out.println("green=====>" + greenApples.size());
        List<Apple> heavyApples = filterApples(apples, app -> app.getWeight() > 150);
        System.out.println("heavy=====>" + heavyApples.size());

        List<Orange> oranges = Arrays.asList(new Orange(10, 5)
                , new Orange(10, 3)
                , new Orange(15, 5)
                , new Orange(15, 3)
                , new Orange(20, 3));
        List<Orange> length_10 = filter(oranges, orange -> orange.getLength() == 10);
        System.out.println("10=====>" + length_10.size());

        List<Apple> redApples = filter(apples, apple -> "red".equals(apple.getColor()));
        System.out.println("red=====>" + redApples.size());

         apples.sort(new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                if(o1.getWeight() > o2.getWeight())
                    return 0;
                return -1;
            }
        });

        System.out.println(apples.get(0).getWeight());

        apples.sort((o1, o2) -> {
            if(o1.getWeight() > o2.getWeight())
                return -1;
            return 0;
        });

        System.out.println(apples.get(0).getWeight());

    }

    public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate predicate){
        List<Apple> res = new ArrayList<>();
        for(Apple apple : inventory){
            if(predicate.test(apple))
                res.add(apple);
        }
        return res;
    }

    public static <T> List<T> filter(List<T> list, Predicate<T> p){
        List<T> res = new ArrayList<>();
        for(T t : list)
            if (p.test(t))
                res.add(t);
        return res;
    }
}
